﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace System.Security.Cryptography
{

    public static class CryptographyExtensions
    {

        /// <summary>
		/// MD5加密
		/// </summary>
		/// <param name="pToEncrypt">需加密字符串</param>
		/// <param name="sKey">密匙（8位）</param>
		/// <returns></returns>
		private static string MD5Encrypt(string pToEncrypt, string sKey)
        {
            StringBuilder ret = new StringBuilder();
            try
            {
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
                des.Key = Encoding.ASCII.GetBytes(sKey);
                des.IV = Encoding.ASCII.GetBytes(sKey);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                foreach (byte b in ms.ToArray())
                {
                    ret.AppendFormat("{0:X2}", b);
                }
            }
            catch (Exception) { }

            return ret.ToString();
        }

        /// <summary>
        /// MD5解密
        /// </summary>
        /// <param name="pToDecrypt">需解密字符串</param>
        /// <param name="sKey">密匙（8位）</param>
        /// <returns></returns>
        private static string MD5Decrypt(string pToDecrypt, string sKey)
        {
            StringBuilder ret = new StringBuilder();
            try
            {
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();

                byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
                for (int x = 0; x < pToDecrypt.Length / 2; x++)
                {
                    int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
                    inputByteArray[x] = (byte)i;
                }
                des.Key = Encoding.ASCII.GetBytes(sKey);
                des.IV = Encoding.ASCII.GetBytes(sKey);

                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                ret = ret.Append(Encoding.Default.GetString(ms.ToArray()));

            }
            catch (Exception) { }

            return ret.ToString();
        }

        public static string Encrypt(this string source, string key)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(source))
                {
                    return null;
                }
                return MD5Encrypt(source, key);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message + Environment.NewLine + ex.StackTrace);
                return null;
            }
        }

        public static string Decrypt(this string source, string key)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(source))
                {
                    return null;
                }
                return MD5Decrypt(source, key);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message + Environment.NewLine + ex.StackTrace);
                return null;
            }
        }

    }

}